/*
 * Content: Java锁机制用法
 * --------------------------------------------------
 * java 中的 Lock锁: https://blog.csdn.net/xyy1028/article/details/107333451
 */

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class java_1112_lock_unlock {
    public static void main(String[] args) {

        // Java锁机制用法
        System.out.println("--------------------Java锁机制用法--------------------");
        // Lock是一个接口，接口的实现类有 ReentrantLock 和内部类 ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
        //      注1: 所以平时使用的 lock() 和 unlock() 都是 ReentrantLock

        Lock lock = new ReentrantLock();            // 默认非公平锁
//        Lock lock = new ReentrantLock(true);      // 公平锁

        Thread thread1 = new MyThreadB(lock);
        Thread thread2 = new MyThreadB(lock);

        // 给线程设置名称
        thread1.setName("XQZ-Thread-OOO");
        thread2.setName("XQZ-Thread-XXX");

        // 启动线程
        thread1.start();
        thread2.start();

    }
}

// 创建线程方式一
class MyThreadB extends Thread {
    static int sign = 1;

    Lock lock;

    public MyThreadB(Lock lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 获取锁
                lock.lock();
                for (int i = 1; i <= 5; ++i) {
                    System.out.println(Thread.currentThread().getName() + "---" + sign++);
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 释放信号量
                lock.unlock();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}